using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Audio;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.GamerServices;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input;
using Microsoft.Xna.Framework.Media;
using System.Windows.Forms;
using DBO;
using ClientUtility;
using WinFormClient;

namespace SquadPlacer
{
    /// <summary>
    /// This is the main type for your game
    /// </summary>
    public class Game1 : Microsoft.Xna.Framework.Game
    {
        GraphicsDeviceManager graphics;
        SpriteBatch spriteBatch;

        private IntPtr DrawSurface;
        Dictionary<string, Texture2D> sprites = new Dictionary<string, Texture2D>();

        Tile[,] data = Board.Instance.Data;

        public static bool MouseEnabled { get; set; }

        public Microsoft.Xna.Framework.Input.ButtonState lpreviousState { get; set; }
        public Microsoft.Xna.Framework.Input.ButtonState rpreviousState { get; set; }
        public string entity_name { get; set; }

        public Entity get(int line, int col)
        {
            return data[line, col].entity;
        }

        public Entity set(int line, int col, string e)
        {
            if (e == "" || e == null)
                return null;
            if (data[line, col] == null)
                data[line, col] = new Tile();
            return data[line, col].entity = EntityFactory.getEntity(e);
        }

        public const int BoardWidth = 8;
        public const int BoardHeight = 2;

        public event EventHandler onAddTroop;
        public event EventHandler onDeleteTroop;

        public Game1(IntPtr DrawSurface)
        {
            entity_name = "";
            MouseEnabled = false;
            Mouse.WindowHandle = DrawSurface;
            graphics = new GraphicsDeviceManager(this);
            Content.RootDirectory = "Content";
            this.DrawSurface = DrawSurface;
            graphics.PreparingDeviceSettings +=
            new EventHandler<PreparingDeviceSettingsEventArgs>(graphics_PreparingDeviceSettings);
            System.Windows.Forms.Control.FromHandle((this.Window.Handle)).VisibleChanged +=
            new EventHandler(Game1_VisibleChanged);
            graphics.PreferredBackBufferWidth = 512;
            graphics.PreferredBackBufferHeight = 128;
            graphics.ApplyChanges();
        }

        public void ClearBoard()
        {
            for (int line = 0; line < BoardHeight; line++)
            {
                for (int col = 0; col < BoardWidth; col++)
                {
                    data[line, col] = new Tile();
                    data[line, col].selected = false;
                    data[line, col].entity = null;
                }
            }
        }

        /// <summary>
        /// Event capturing the construction of a draw surface and makes sure this gets redirected to
        /// a predesignated drawsurface marked by pointer drawSurface
        /// </summary>
        ///<param name="sender"></param>
        ///<param name="e"></param>
        void graphics_PreparingDeviceSettings(object sender, PreparingDeviceSettingsEventArgs e)
        {
                e.GraphicsDeviceInformation.PresentationParameters.DeviceWindowHandle = DrawSurface;
        }

        /// <summary>
        /// Occurs when the original gamewindows' visibility changes and makes sure it stays invisible
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Game1_VisibleChanged(object sender, EventArgs e)
        {
                if (System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible == true)
                    System.Windows.Forms.Control.FromHandle((this.Window.Handle)).Visible = false;
        }
 
        /// <summary>
        /// Allows the game to perform any initialization it needs to before starting to run.
        /// This is where it can query for any required services and load any non-graphic
        /// related content.  Calling base.Initialize will enumerate through any components
        /// and initialize them as well.
        /// </summary>
        protected override void Initialize()
        {
            // TODO: Add your initialization logic here
            base.Initialize();
            ClearBoard();
        }

        /// <summary>
        /// LoadContent will be called once per game and is the place to load
        /// all of your content.
        /// </summary>
        protected override void LoadContent()
        {
            // Create a new SpriteBatch, which can be used to draw textures.
            spriteBatch = new SpriteBatch(GraphicsDevice);
            ResourceLoader.loadResources(Content);
            // TODO: use this.Content to load your game content here
        }

        /// <summary>
        /// UnloadContent will be called once per game and is the place to unload
        /// all content.
        /// </summary>
        protected override void UnloadContent()
        {
            // TODO: Unload any non ContentManager content here
        }

        /// <summary>
        /// Allows the game to run logic such as updating the world,
        /// checking for collisions, gathering input, and playing audio.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Update(GameTime gameTime)
        {
            if (!MouseEnabled)
                return;
            // Allows the game to exit
            if (GamePad.GetState(PlayerIndex.One).Buttons.Back == Microsoft.Xna.Framework.Input.ButtonState.Pressed)
                this.Exit();

            MouseState ms = Mouse.GetState();

            //ignore mouse outside component
            if (MainForm.ActiveForm != null)
            {
                PictureBox pb = MainForm.ActiveForm.Controls.Find("pictureBox1", true).FirstOrDefault() as PictureBox;
                if ((ms.X < 0) || (ms.Y < 0) || (ms.X > pb.Width) || (ms.Y > pb.Height))
                    lpreviousState = Microsoft.Xna.Framework.Input.ButtonState.Released;
            }

            if ((ms.LeftButton == Microsoft.Xna.Framework.Input.ButtonState.Released) && (lpreviousState == Microsoft.Xna.Framework.Input.ButtonState.Pressed))
            {
                if (entity_name == "")
                    return;

                int whereX = ms.X / 64;
                int whereY = ms.Y / 64;

                if (ms.Y < 0 || ms.X < 0 ||
                    whereX < 0 || whereX >= 8 ||
                    whereY < 0 || whereY >= 2)
                    return;

                if (data[whereY, whereX].entity == null)
                {
                    data[whereY, whereX].entity = EntityFactory.getEntity(entity_name);
                    onAddTroop.Invoke(entity_name.ToLower(), null);
                }
            }

            if ((ms.RightButton == Microsoft.Xna.Framework.Input.ButtonState.Released) && (rpreviousState == Microsoft.Xna.Framework.Input.ButtonState.Pressed))
            {
                int whereX = ms.X / 64;
                int whereY = ms.Y / 64;

                if (ms.Y < 0 || ms.X < 0 ||
                    whereX < 0 || whereX >= 8 ||
                    whereY < 0 || whereY >= 2)
                    return;

                if (data[whereY, whereX].entity != null)
                {
                    data[whereY, whereX].entity = null;
                    onDeleteTroop(data[whereY, whereX].entity.Name.ToLower(), null);
                }
            }

            lpreviousState = ms.LeftButton;
            rpreviousState = ms.RightButton;
            base.Update(gameTime);
        }

        /// <summary>
        /// This is called when the game should draw itself.
        /// </summary>
        /// <param name="gameTime">Provides a snapshot of timing values.</param>
        protected override void Draw(GameTime gameTime)
        {
            // TODO: Add your drawing code here

            //clear screen
            GraphicsDevice.Clear(Color.GhostWhite);

            spriteBatch.Begin();

            for (int i = 0; i < 8; ++i)
            {
                for (int j = 0; j < 2; ++j)
                {
                    if (data[j, i].selected == true)
                        spriteBatch.Draw(ResourceLoader.getTexture("selected"), new Microsoft.Xna.Framework.Vector2(64 * i, 64 * j), Color.White);
                    else
                        spriteBatch.Draw(ResourceLoader.getTexture("tile"), new Microsoft.Xna.Framework.Vector2(64 * i, 64 * j), Color.White);

                    if (data[j, i].entity != null)
                    {
                        Entity e = data[j, i].entity;
                        spriteBatch.Draw(ResourceLoader.getTexture(e.Name), new Microsoft.Xna.Framework.Vector2(64 * i, 64 * j), Color.White);
                    }
                }
            }

            spriteBatch.End();
            base.Draw(gameTime);
        }
    }
}
